<template>
  <div>
    <el-upload
      class="SingleUpload"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="doUpload"
    >
      <div>
        <div>
          <el-button type="primary">上传图片</el-button>
        </div>
        <div class="preview" v-if="imageUrl">
          <img v-if="imageUrl" :src="imageUrl" />
        </div>
      </div>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { uploadFile } from "@/api/common-feature/index.ts";
import { ref } from "vue";
import { ElMessage, UploadRawFile, UploadRequestOptions } from "element-plus";

let imageUrl = ref<string>("");

const doUpload = (options: UploadRequestOptions) => {
  console.log("doUpload:", options);
  uploadFile(options.file).then((res: any) => {
    console.log("upload:", res.material.ossUrl);
    imageUrl.value = res.material.ossUrl;
  });
};

const beforeUpload = (file: UploadRawFile) => {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.error("上传图片不能大于2M");
    return false;
  }
  return true;
};
</script>

<style scoped lang="scss">
.SingleUpload {
  .preview {
    width: 50px;
    height: 50px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
